/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huan.study.flink.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * flink stream word count
 */
public class StreamingJob {

    public static void main(String[] args) throws Exception {
        // 创建一个stream执行上下文
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 构建一个socket数据源，用于从本地9999端口获取数据
        env.socketTextStream("localhost", 9999)
                // 将每行数据以","分割，此时每行就是一个数组
                .flatMap(new FlatMapFunction<String, String[]>() {
                    @Override
                    public void flatMap(String input, Collector<String[]> collector) throws Exception {
                        collector.collect(input.split(","));
                    }
                })
                // 将每个词包装成 （词,1） 这种格式
                .flatMap(new FlatMapFunction<String[], Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String[] words, Collector<Tuple2<String, Integer>> collector) throws Exception {
                        for (String word : words) {
                            collector.collect(new Tuple2<>(word, 1));
                        }
                    }
                })
                // 根据第一个词进行分组
                .keyBy(0)
                // 时间窗口为10s
                .timeWindow(Time.seconds(10))
                // 根据第二个字段进行统计
                .sum(1)
                // 数据统计数据
                .print();

        // 执行程序
        env.execute("StreamingJob");
    }
}
